package com.lipi.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lipi.common.utils.R;
import com.lipi.mall.cart.constant.CartConstant;
import com.lipi.mall.cart.feign.ProductFeignService;
import com.lipi.mall.cart.interceptor.CartInterceptor;
import com.lipi.mall.cart.service.CartService;
import com.lipi.mall.cart.vo.Cart;
import com.lipi.mall.cart.vo.CartItem;
import com.lipi.mall.cart.vo.SkuInfoVO;
import com.lipi.mall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //判断redis中是否已存在该商品数据,不存在：新增操作,存在：修改操作。
        String res = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(res)) {
            //新增
            CartItem cartItem = new CartItem();

            //远程查询sku信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);

                SkuInfoVO data = r.get("skuInfo", new TypeReference<SkuInfoVO>() {
                });


                cartItem.setCheck(true);
                cartItem.setCount(Integer.valueOf(num));
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            }, executor);

            //获取skuId对应的销售属性组合
            CompletableFuture<Void> getSkuAttrTask = CompletableFuture.runAsync(() -> {
                        List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                        cartItem.setSkuAttr(skuSaleAttrValues);
                    }
                    , executor);

            //阻塞等待
            CompletableFuture.allOf(getSkuInfoTask, getSkuAttrTask).get();

            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);

            return cartItem;
        } else {
            //修改,修改数量即可
            CartItem cartItem = JSON.parseObject(res, new TypeReference<CartItem>() {
            });


            cartItem.setCount(Integer.valueOf(num) + cartItem.getCount());


            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

            return cartItem;
        }


    }

    /**
     * 根据登录状态和skuId获得指定购物项
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(str, CartItem.class);
    }

    /**
     * 获取购物车列表
     *
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();


        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 用户已登录,使用用户购物车
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            //2、若离线购物车存在数据,先合并购物车
            String tempCartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                //合并
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                //清空离线购物车数据
                clearCart(tempCartKey);
            }

            //3、获取用户购物车数据(已合并离线购物车数据)
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        } else {
            // 用户未登录,操作离线购物车
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();

            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        }
        return cart;

    }

    /**
     * 获取给定用户标识下所有的购物项
     * redis存储结构：mall:cart:${用户标识}->hash<skuId,cartItem>
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


    /**
     * 从redis中获取要操作的购物车操作对象
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 1、判断是用户购物车还是离线购物车
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        String redisKey = "";
        if (userInfoTo.getUserId() != null) {
            //用户已登录,使用用户购物车
            redisKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();

        } else {
            //用户未登录,使用离线购物车
            redisKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(redisKey);
        return operations;
    }


    @Override
    public void clearCart(String cartkey) {
        redisTemplate.delete(cartkey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);

        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);

    }


    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        if (num > 0) {
            //修改购物项数量
            CartItem cartItem = getCartItem(skuId);
            cartItem.setCount(num);

            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);
        } else {
            //删除购物项
            deleteItem(skuId);
        }

    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        Long userId = userInfoTo.getUserId();
        if (userId == null) {
            //用户未登录
            return null;
        }

        List<CartItem> collect = getCartItems(CartConstant.CART_PREFIX + userId).stream().filter(item -> {
            return item.getCheck();
        }).map(
                item -> {
                    //更新skuId价格
                    R r = productFeignService.getPrice(item.getSkuId());
                    item.setPrice(r.getData(new TypeReference<BigDecimal>(){}));

                    return item;
                }
        ).collect(Collectors.toList());

        return collect;

    }
}
